package com.watson.juc.pc;

import java.sql.Connection;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author watson
 * @date 2021/7/29 13:37
 * @Description: TODO
 **/
public class Jucabc {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}


class Data1 {
    //资源类
    private int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    public void increment() throws InterruptedException {
        lock.lock();
        try {
//        if (num!=0){
            while (num != 0) {
                //等待
                condition.await();
            }
            num++;
            //通知其他线程，+1 完毕
            //唤醒全部
            condition.signalAll();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + "==>" + num);
    }

    public synchronized void decrement() throws InterruptedException {
        lock.lock();

        try {
            //唤醒全部
            condition.signal();
            while (num == 0) {
//        if (num == 0) {
                //等待
                condition.await();
            }
            num--;
            //通知其他线程，-1完毕
            //唤醒全部
            condition.signalAll();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }

        System.out.println(Thread.currentThread().getName() + "==>" + num);
    }

}
